import { PureComponent,Fragment  } from "react";
import { SearchBar,Carousel,Grid,Flex,TabBar,Button,PullToRefresh,ListView} from "antd-mobile"
import { ActivityIndicator } from 'antd-mobile';
import { connect } from 'dva';
import { Row, Col,Select } from 'antd';
import $ from 'jquery';
import { handleImg, goToPage,isNull,handleOSS } from "../../utils/helper";
import {IntlProvider, addLocaleData,FormattedMessage} from 'react-intl';
import localeData from '../../../public/lang/data.json';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import MToast from '../../components/Util/MToast';
import ReactDOM from 'react-dom';
import Masonry from 'masonry-layout';  //实现瀑布流
import imagesloaded  from 'imagesloaded' //监听图片加载
import InfiniteScroll from 'react-infinite-scroller' //下拉加载
const Option = Select.Option;
@connect(() => {
  return ({

  })
})

export default class MelaShop extends PureComponent{
  constructor(props){
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2 // rowHasChanged(prevRowData, nextRowData); 用其进行数据变更的比较
    })
    this.state = {
      carouselItem:[],
      loading:true,
      dataSource,
     newsList:[],
     pages:{
        pageNum:1,
       pageSize:20
     },
      hasMore: true,
      refreshing: true,
      isLoading: true,
      selectedTab: 'redTab',
      onImg:true,
      locale:'it',
      isOption:false,
      height: document.documentElement.clientHeight,
      useBodyScroll: true,
      IsImage:false,
      data:[],//整体的数据
      leftData:[],//左边的数据
      rightData:[],//右边的数据,
      dataSource1:[],
      dataImg : []
    }
  }
  componentDidUpdate() {
    if (this.state.useBodyScroll) {
      document.body.style.overflow = 'auto';
    } else {
      document.body.style.overflow = 'hidden';
    }
  }
  componentDidMount() {
    let {dataImg,dataSource1} = this.state;
    console.log(ReactDOM.findDOMNode(this.lv))
    // const hei = this.state.height - ReactDOM.findDOMNode(this.lv).offsetTop;
    console.log(this.state.height)
    console.log(dataImg)
    // setTimeout(() => {
    //
    //   this.setState({
    //
    //     height: hei,
    //
    //   });
    // }, 1500);
    // this.waterfall('main1','box1');
    window.onload = ()=>{
      this.waterfall('main1','box1');

    }
  }
  componentWillMount(){
    let {dispatch,location} = this.props;
this.bannerList();
 // this.goodContent(this.state.pages);
this.goodContent1()
    if(localStorage.locale=='it'){
      this.setState({
        locale:'it',
        isOption:false
      })
    }else if(localStorage.locale=='zh'){
      this.setState({
        locale:'zh',
        isOption:true
      })
    }else{
      localStorage.setItem("locale",'it')
      this.setState({
        locale:'it',
        isOption:false
      })
    }
    // this.waterfall('main1','box1');

  }

  bannerList(){
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_banner_list",
          params: [
          ],
          _c: "app_banner_list"
        },
        callback: (result) => {
          let { data } = result;
          this.setState({
            carouselItem:data,
            loading:false,

          })
          console.log(data)

        }
      }
    });
  };
   waterfall(parent,box){
    //获取main元素
    var oparent = document.getElementById(parent);
console.log(oparent)
    //获取所有 box 元素
    var obox = this.getClass('box1');
console.log(obox)
    //获取每行能放多少个 居中摆放
    var w = document.body.clientWidth||document.documentElement.clientWidth;
    //var w =1000;
    var oneWidth = obox[0].offsetWidth;
    var num = Math.floor(w/oneWidth);
    main.style.width = num*oneWidth+'px';

    //瀑布流原理  left-下标*图片width top-上面图片高
    var hrr = [];
    for(var i=0;i<obox.length;i++){
      if(i<num){
        hrr.push(obox[i].offsetHeight);
      }else{
        var min = Math.min.apply(null,hrr);
        var index = this.getindex(hrr,min);
        obox[i].style.position = 'absolute';
        obox[i].style.left = index*oneWidth+'px';
        obox[i].style.top = min+'px';
        hrr[index] += obox[i].offsetHeight;
      }
    }
    console.log(hrr);
  }
  getindex(hrr,h){
    for(var i=0;i<hrr.length;i++){
      if(hrr[i]==h){
        return i;
      }
    }
  }
  getClass(a){
    var doms = document.getElementsByTagName('*');
    console.log(doms)
    var reg = new RegExp('\\b'+a+'\\b');
    console.log(reg)
    //var reg = '/^\b'+a+'\b$/';
    var arr = [];
    for(var i=0;i<doms.length;i++){
      if(reg.test(doms[i].className)){
        arr.push(doms[i]);
      }
    }
    return arr;
  }
 getNaturalWidth=(img)=> {
    var image = new Image()
    image.src = img.src
    var naturalWidth = image.width
    return naturalWidth
  }

  goodContent1(){
    let {dispatch,location,dataSource1,dataImg} = this.props;
    let _this = this;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "lv/data?_c=app_goods_page_list",
          params: [
            {
              key: "page_index",
              value: 1
            },
            {
              key: "page_size",
              value: 20
            },
          ],
          _c: "app_goods_page_list"
        },
        callback: (result) => {
          let { data } = result;
          console.log(data.list);
          console.log(data.list[0].store_id)
          localStorage.setItem("store_id",data.list[0].store_id)
this.setState({
  dataSource1:data.list.slice(0,5),
  dataImg:data.list.slice(5,10)
})
          const dataImg=data.list.slice(5,data.count);
          console.log(dataSource1,dataImg)
          window.onscroll = ()=>{
            // alert("11")
            //当滚动到最后一张图片高度一般时刷新新数据
            var boxs = this.getClass('box1');
            var oneh2 = boxs[boxs.length-1].offsetTop;
            var oneh = boxs[boxs.length-1].offsetHeight/2;
            var top = document.body.scrollTop || document.documentElement.scrollTop;
            var twoh = document.body.clientHeight||document.documentElement.clientHeight;

            if(oneh2+oneh<top+twoh){
              for(var i=0;i<dataImg.length;i++){
                var main = document.getElementById('main1');
                var cdiv = document.createElement('div');
                cdiv.className = 'box1';
                var cpic = document.createElement('div');
                cpic.className = 'pic';
                var cimg = document.createElement('img');
                cimg.src =  dataImg[i].img_url;
                main.appendChild(cdiv);
                cdiv.appendChild(cpic);
                cpic.appendChild(cimg);
              }
            }
            this.waterfall('main1','box1');
          }
// this.getHW(data.list)
        }
      }
    });
  }
  goodContent(pages){
    let {dispatch,location} = this.props;
    let _this = this;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "lv/data?_c=app_goods_page_list",
          params: [
            {
              key: "page_index",
              value: 1
            },
            {
              key: "page_size",
              value: 20
            },
          ],
          _c: "app_goods_page_list"
        },
        callback: (result) => {
          let { data } = result;
          console.log(data.list);
          console.log(data.list[0].store_id)
          localStorage.setItem("store_id",data.list[0].store_id);
          // this.getHW(data.list)
          const len = data.list.length;
          if(data.count/20>=this.state.pages.pageNum){
            this.state.pages.pageNum++;
            this.state.newsList=[...this.state.newsList,...data.list]
            this.setState({
              newsList:this.state.newsList,
              dataSource: this.state.dataSource.cloneWithRows(this.state.newsList),
              isLoading: false,
              pages:this.state.pages,
            })
          }else{
            this.setState({
              newsList:this.state.newsList,
              dataSource: this.state.dataSource.cloneWithRows(data.list),
              isLoading: false,
              pages:this.state.pages,
            })
          }
          this.setState({
            refreshing:false
          })

        }
      }
    });
  }
  // 滑动到底部时加载更多
  onEndReached = (event) => {//触底加载
    if (this.state.isLoading) {
      return;
    }
    this.setState({ isLoading: true });
    setTimeout(() => {
      this.goodContent(this.state.pages)
    }, 600);
  }


  goodList() {
    let { dataSource1} = this.state;

    if (!dataSource1 || dataSource1.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div id="main1">
          {dataSource1.map((i,k) => (
            <div class="box1">
              <div class="pic">
                <img src={handleOSS(i.img_url)} />
              </div>
            </div>

          ))}
        </div>

      )
    }
  }
  handleDetail=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/goodsDetail?id="+i.id+"&store_id="+i.store_id }, isReplace: false })
  }
  handleAdd=(e,i)=>{
    // console.log(i);
    let {dispatch} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "cart/add",
          params: [
            {
              key: "goods_id",
              value: i.id
            },
            {
              key: "goods_name",
                value: i.goods_name
            },
            {
              key: "img_url",
                value: i.img_url
            },
            {
              key: "price",
                value: i.price
            },
            {
              key: "quantity",
                value: 1
            }
          ]
        },
        callback: (result) => {
          let { data } = result;
       console.log(data)
            MToast.info(T(localeData[localStorage.locale].goodsDetailCartInfo,3, null, false));

        }
      }
    })
  }
  chooseLocale=(value)=>{
    const {locale}=this.state;
    // // const localeValue = value;
    localStorage.setItem("locale",value)
    this.setState({
      locale: value,
      onImg:false
    });
    console.log(value);
  }
  onRefresh=()=>{
    this.state.pages.pageNum = 1;
    this.setState({ refreshing: true, isLoading: true ,pages:this.state.pages,newsList:[]});
    setTimeout(() => {
      this.goodContent(this.state.pages);
    }, 600);
    // this.bannerList();

  }
  handleImageLoaded=()=>{
    let {IsImage}=this.state;
    this.setState({
      IsImage:true
    })
  }

  render(){
    let {dispatch} = this.props;
    let {carouselItem,dataSource,dataSourceObj,loading,onImg,isOption,IsImage,data,hasMore,leftData,rightData,dataSource1} = this.state;
    const messages = localeData[localStorage.locale]
    console.log(this.state.locale,isOption)
    // console.log(leftData,rightData)
    const row =(rowData, sectionID, rowID)=>{
      // console.log(rowData)
      return (
        <div class="box1">
          <div class="pic">
            <img src={handleOSS(rowData.img_url)} />
          </div>
        </div>
      )
    }
    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text="正在加载" animating={true} />
        </div>
      )
    }
    return(
      <div style={{background:'rgb(249, 247, 247)'}}>
        <IntlProvider
          locale={ this.state.locale } messages={messages}
        >
          <div>
            {isOption?
              <div >
                {/*{onImg?<img src="image/china.png" style={{position:'fixed',top:'3%',left:'2%',zIndex:'100',width:'16px',height:'16px'}}/>:''}*/}
                <Select
                defaultValue="zh"
                onChange={this.chooseLocale}
                bordered={false}
                style={{position:'fixed',top:'3%',left:'4%',zIndex:'200',width:'20%',}}
              >
                {/*<Option key="cn" value="en">English</Option>*/}
                <Option  key="it" value="it">
                  <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="IT">
                    <img src="image/Italy.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                    IT
                  </div>
                </Option>
                <Option  key="en" value="zh" >
                  <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="ZH">
                    <img src="image/china.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                    CN
                  </div>
                </Option>

              </Select>
              </div>:
              <div>
                {/*{onImg?<img src="image/Italy.png" style={{position:'fixed',top:'3%',left:'2%',zIndex:'100',width:'16px',height:'16px'}}/>:""}*/}
                <Select
                  defaultValue="it"
                  onChange={this.chooseLocale}
                  bordered={false}
                  style={{position:'fixed',top:'3%',left:'4%',zIndex:'200',width:'20%',}}
                >
                  {/*<Option key="cn" value="en">English</Option>*/}
                  <Option  key="it" value="it">
                    <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="IT">
                    <img src="image/Italy.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                      IT
                    </div>
                  </Option>
                  <Option  key="en" value="zh" >
                    <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="ZH">
                    <img src="image/china.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                      CN
                    </div>
                  </Option>

                </Select>
              </div>
            }


          <div maxLength={8} style={{position:'fixed',top:'2%',left:'3%',width:'92%',zIndex:'100',height:'44px',border:'1px solid #ddd',borderRadius:'15px',background:"#fff"}} onClick={()=>{goToPage({ dispatch, config: { url: "/searchPage" }, isReplace: false })}}>
            <div style={{position:'absolute',top:'25%',left:'37%'}}>
              <img src="image/search_24px.png" style={{width:'24px',height:'24px'}}/><span style={{color:'#C9C9C9',fontSize:'13px'}}>{messages.searchPlaceholder}</span>
            </div>
          </div>
          </div>
          <Carousel
            autoplay={true}
            infinite
            autoplayInterval={10000}
            speed={400}
          >
            {this.state.carouselItem.map((i,k) => (
              <a
                key={k}
                style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
              >
                <img
                  src={handleOSS(i.url)}
                  alt=""
                  style={{ width: '100%', verticalAlign: 'top',height:'237px' }}
                  onLoad={() => {
                    // fire window resize event to change height
                    this.setState({ imgHeight: '237px' });
                  }}
                />
              </a>
            ))}
          </Carousel>
          <p style={{color:'#2E2D35',fontSize:'17px',margin:'16px 16px 0px'}}>Più venduti</p>
          {/*<div id="main1">*/}
            {/*<ListView*/}
              {/*ref={el => this.lv = el}*/}
              {/*dataSource={this.state.dataSource}*/}
              {/*renderRow={row}*/}
              {/*useBodyScroll*/}
              {/*onEndReachedThreshold={10}*/}
              {/*onEndReached={this.onEndReached}*/}
              {/*pageSize={5}*/}
              {/*scrollEventThrottle={1}*/}
              {/*renderFooter={() => (<div style={{ padding:'0px 0px 40px' , textAlign: 'center' }}>*/}
                {/*{this.state.isLoading ? 'Loading...' : 'Loaded'}*/}
              {/*</div>)}*/}
              {/*className="mela"*/}
              {/*pullToRefresh={<PullToRefresh*/}
                {/*refreshing={this.state.refreshing}*/}
                {/*onRefresh={this.onRefresh}*/}
              {/*/>}*/}
            {/*>*/}

            {/*</ListView>*/}
          {/*</div>*/}



          {/*{this.goodList()}*/}
          <div id="main1">
            {dataSource1.map((i,k) => (
              <div class="box1">
                <div class="pic">
                  <img src={handleOSS(i.img_url)} />
                  <div style={{overflow:'hidden',margin:'10% 0px 0px',width:'100%'}}>
                    <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',}}>{i.goods_name}</p>
                    <div style={{overflow:'hidden',marginTop:'8px'}}>
                      <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{i.price}</div>
                      <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,i) }}>
                        <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                      </div>
                    </div>

                  </div>
                </div>
              </div>

            ))}
          </div>

          <div style={{position:'fixed',bottom:'0px',left:'0px',width:'100%'}}>
            <TabBar
              unselectedTintColor="#949494"
              tintColor="#F09600"
              barTintColor="white"
              hidden={this.state.hidden}
            >
              <TabBar.Item
                title={messages.home}
                key="Life"
                icon={<div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/home2.png) center center /  21px 21px no-repeat' }}
                />
                }
                selectedIcon={<div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/home3.png) center center /  21px 21px no-repeat' }}
                />
                }
                selected={this.state.selectedTab === 'redTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'redTab',
                  });
                  goToPage({ dispatch, config: { url: "/shop_home" }, isReplace: false })
                }}
                data-seed="logId"
              >

              </TabBar.Item>
              <TabBar.Item
                icon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/category.png) center center /  21px 21px no-repeat' }}
                  />
                }
                selectedIcon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/category1.png) center center /  21px 21px no-repeat' }}
                  />
                }
                title={messages.category}
                key="Koubei"

                selected={this.state.selectedTab === 'blueTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'blueTab',
                  });
                  goToPage({ dispatch, config: { url: "/category" }, isReplace: false })
                }}
                data-seed="logId1"
              >

              </TabBar.Item>
              <TabBar.Item
                icon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/cart4.png) center center /  21px 21px no-repeat' }}
                  />
                }
                selectedIcon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/cart5.png) center center /  21px 21px no-repeat' }}
                  />
                }
                title={messages.cart}
                key="Friend"
                selected={this.state.selectedTab === 'greenTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'greenTab',
                  });
                  goToPage({ dispatch, config: { url: "/goodcart" }, isReplace: false })
                }}
              >
              </TabBar.Item>
              <TabBar.Item
                icon={{ uri: 'image/my.png' }}
                selectedIcon={{ uri: 'image/my1.png' }}
                title={messages.my}
                key="my"
                selected={this.state.selectedTab === 'yellowTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'yellowTab',
                  });
                  goToPage({ dispatch, config: { url: "/my" }, isReplace: false })
                }}
              >
              </TabBar.Item>
            </TabBar></div>
        </IntlProvider>


      </div>
    )
  }
}
